<template>
  <view class="comment-section">
    <scroll-view scroll-y="true" class="comment-list" :style="{ height: scrollHeight + 'px' }">
      <view v-for="(comment, index) in comments" :key="index" class="comment-item">
        <view class="comment-header">
          <text class="comment-user">{{ comment.username }}</text>
          <text class="comment-time">{{ formatTime(comment.time) }}</text>
        </view>
        <view class="comment-content">{{ comment.content }}</view>
        <view class="comment-actions">
          <text class="action-btn" @click="toggleLike(index)">
            {{ comment.likes || 0 }} {{ comment.isLiked ? '取消点赞' : '点赞' }}
          </text>
          <text class="action-btn" @click="prepareReply(index, null)">回复</text>
        </view>

        <!-- 回复列表 -->
        <view v-if="comment.replies" class="replies-container">
          <!-- 显示前2条回复 -->
          <view v-for="(reply, replyIndex) in visibleReplies(comment.replies, index)" :key="replyIndex"
            class="reply-item">
            <view class="reply-header">
              <text class="reply-user">{{ reply.username }}</text>
              <text class="reply-time">{{ formatTime(reply.time) }}</text>
              <text class="reply-to" v-if="reply.toUser">回复 @{{ reply.toUser }}</text>
            </view>
            <view class="reply-content">{{ reply.content }}</view>

            <!-- 对回复的回复操作按钮 -->
            <view class="reply-actions" v-if="!reply.isReplying">
              <text class="action-btn" @click="prepareReply(index, replyIndex)">回复</text>
            </view>

            <!-- 嵌套回复列表 -->
            <view v-if="reply.replies && reply.replies.length > 0" class="nested-replies">
              <view v-for="(nestedReply, nestedIndex) in visibleNestedReplies(reply.replies, index, replyIndex)"
                :key="nestedIndex" class="nested-reply-item">
                <view class="nested-reply-header">
                  <text class="nested-reply-user">{{ nestedReply.username }}</text>
                  <text class="nested-reply-time">{{ formatTime(nestedReply.time) }}</text>
                  <text class="nested-reply-to" v-if="nestedReply.toUser">回复 @{{ nestedReply.toUser }}</text>
                </view>
                <view class="nested-reply-content">{{ nestedReply.content }}</view>
              </view>

              <!-- 展开/收起嵌套回复按钮 -->
              <view v-if="reply.replies.length > 2" class="expand-nested-btn"
                @click="toggleNestedReplies(index, replyIndex)">
                {{ reply.expanded ? '收起回复' : `查看全部${reply.replies.length}条回复` }}
              </view>
            </view>
          </view>

          <!-- 展开/收起按钮 -->
          <view v-if="comment.replies.length > 2" class="expand-btn" @click="toggleReplies(index)">
            {{ comment.expanded ? '收起回复' : `查看全部${comment.replies.length}条回复` }}
          </view>
        </view>
      </view>
    </scroll-view>

    <view class="comment-input">
      <input v-model="inputContent" :placeholder="getPlaceholderText()" class="input" @confirm="submitContent"
        :focus="isInputFocused" ref="inputRef" />
      <button @click="submitContent" class="submit-btn">发送</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed, nextTick } from 'vue'

// 评论数据
const comments = ref([
  {
    username: '用户1',
    content: '这是一个测试评论',
    time: new Date().getTime() - 3600000,
    likes: 5,
    isLiked: false,
    expanded: false, // 控制回复是否展开
    replies: [
      {
        username: '用户2',
        toUser: '用户1',
        content: '这是对测试评论的回复1',
        time: new Date().getTime() - 1800000,
        expanded: false,
        replies: [
          {
            username: '用户3',
            toUser: '用户2',
            content: '这是对回复1的回复1',
            time: new Date().getTime() - 900000
          },
          {
            username: '用户4',
            toUser: '用户2',
            content: '这是对回复1的回复2',
            time: new Date().getTime() - 360000
          }
        ]
      },
      {
        username: '用户3',
        toUser: '用户1',
        content: '这是对测试评论的回复2',
        time: new Date().getTime() - 900000,
        expanded: false,
        replies: []
      },
      {
        username: '用户4',
        toUser: '用户1',
        content: '这是对测试评论的回复3',
        time: new Date().getTime() - 360000,
        expanded: false,
        replies: []
      },
      {
        username: '用户5',
        toUser: '用户1',
        content: '这是对测试评论的回复4',
        time: new Date().getTime() - 180000,
        expanded: false,
        replies: []
      }
    ]
  },
  {
    username: '用户2',
    content: 'UniApp的组合式API真好用',
    time: new Date().getTime() - 7200000,
    likes: 3,
    isLiked: true,
    expanded: false,
    replies: [
      {
        username: '用户3',
        toUser: '用户2',
        content: '确实很好用',
        time: new Date().getTime() - 5400000,
        expanded: false,
        replies: [
          {
            username: '用户4',
            toUser: '用户3',
            content: '我也这么认为',
            time: new Date().getTime() - 3600000
          }
        ]
      },
      {
        username: '用户4',
        toUser: '用户2',
        content: '我正在学习使用',
        time: new Date().getTime() - 3600000,
        expanded: false,
        replies: []
      }
    ]
  }
])
const isInputFocused = ref(false)
// 输入框内容
const inputContent = ref('')
// 当前正在回复的评论索引和回复索引
const replyTo = ref({
  commentIndex: -1,
  replyIndex: null
})
// 输入框引用
const inputRef = ref(null)
// 滚动区域高度
const scrollHeight = ref(500)

// 获取占位符文本
const getPlaceholderText = () => {
  if (replyTo.value.commentIndex === -1) {
    return '写下你的评论...'
  }

  const comment = comments.value[replyTo.value.commentIndex]
  if (replyTo.value.replyIndex === null) {
    return `回复 @${comment.username}`
  }

  const reply = comment.replies[replyTo.value.replyIndex]
  return `回复 @${reply.username}`
}

// 准备回复
const prepareReply = (commentIndex, replyIndex) => {
  replyTo.value = {
    commentIndex: commentIndex,
    replyIndex: replyIndex
  }
  inputContent.value = ''
  isInputFocused.value = true
  nextTick(() => {
    // inputRef.value.focus()
  })
}

// 提交内容（评论或回复）
const submitContent = () => {
  if (!inputContent.value.trim()) {
    uni.showToast({
      title: '内容不能为空',
      icon: 'none'
    })
    return
  }

  if (replyTo.value.commentIndex === -1) {
    // 提交新评论
    const comment = {
      username: '当前用户',
      content: inputContent.value.trim(),
      time: new Date().getTime(),
      likes: 0,
      isLiked: false,
      expanded: false,
      replies: []
    }
    comments.value.unshift(comment)
  } else {
    const { commentIndex, replyIndex } = replyTo.value
    const comment = comments.value[commentIndex]

    if (replyIndex === null) {
      // 提交对评论的回复
      const reply = {
        username: '当前用户',
        toUser: comment.username,
        content: inputContent.value.trim(),
        time: new Date().getTime(),
        expanded: false,
        replies: []
      }

      if (!comment.replies) {
        comment.replies = []
      }

      comment.replies.unshift(reply)
    } else {
      // 提交对回复的回复
      const reply = comment.replies[replyIndex]
      const nestedReply = {
        username: '当前用户',
        toUser: reply.username,
        content: inputContent.value.trim(),
        time: new Date().getTime(),
        expanded: false,
        replies: []
      }

      if (!reply.replies) {
        reply.replies = []
      }

      reply.replies.unshift(nestedReply)

      // 如果父回复是收起的，自动展开
      if (!comment.expanded) {
        comment.expanded = true
      }

      // 如果嵌套回复是收起的，自动展开
      if (reply.replies.length > 2 && !reply.expanded) {
        reply.expanded = true
      }
    }
  }

  // 重置状态
  inputContent.value = ''
  replyTo.value = {
    commentIndex: -1,
    replyIndex: null
  }
}

// 点赞/取消点赞
const toggleLike = (index) => {
  if (comments.value[index].isLiked) {
    comments.value[index].likes--
  } else {
    comments.value[index].likes++
  }
  comments.value[index].isLiked = !comments.value[index].isLiked
}

// 切换回复的展开/收起状态
const toggleReplies = (index) => {
  comments.value[index].expanded = !comments.value[index].expanded
}

// 切换嵌套回复的展开/收起状态
const toggleNestedReplies = (commentIndex, replyIndex) => {
  comments.value[commentIndex].replies[replyIndex].expanded = !comments.value[commentIndex].replies[replyIndex].expanded
}

// 获取可见的回复（默认显示2条）
const visibleReplies = (replies, commentIndex) => {
  if (!comments.value[commentIndex].expanded) {
    return replies.slice(0, 2)
  }
  return replies
}

// 获取可见的嵌套回复（默认显示2条）
const visibleNestedReplies = (replies, commentIndex, replyIndex) => {
  const reply = comments.value[commentIndex].replies[replyIndex]
  if (!reply.expanded) {
    return replies.slice(0, 2)
  }
  return replies
}

// 时间格式化
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now.getTime() - timestamp

  if (diff < 86400000) { // 1天内
    return `${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
  } else if (diff < 2592000000) { // 30天内
    return `${date.getMonth() + 1}-${date.getDate()}`
  } else {
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
  }
}

// 计算滚动区域高度
onMounted(() => {
  uni.getSystemInfo({
    success: (res) => {
      const query = uni.createSelectorQuery().in(this)
      query.select('.comment-input').boundingClientRect(data => {
        scrollHeight.value = res.windowHeight - data.height - 20
      }).exec()
    }
  })
})
</script>

<style scoped>
.comment-section {
  padding: 20rpx;
  background-color: #f5f5f5;
}

.comment-list {
  margin-bottom: 20rpx;
}

.comment-item {
  background-color: #fff;
  padding: 20rpx;
  margin-bottom: 20rpx;
  border-radius: 10rpx;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.comment-user {
  font-weight: bold;
  color: #333;
}

.comment-time {
  color: #999;
  font-size: 24rpx;
}

.comment-content {
  color: #666;
  line-height: 1.5;
  margin-bottom: 15rpx;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
  gap: 30rpx;
}

.action-btn {
  color: #007aff;
  font-size: 24rpx;
}

/* 回复列表样式 */
.replies-container {
  margin-top: 20rpx;
  padding-left: 40rpx;
  /* 缩进效果 */
  border-left: 2rpx solid #eee;
  /* 可选：添加左边框增强视觉效果 */
}

.reply-item {
  background-color: #f9f9f9;
  padding: 15rpx;
  margin-bottom: 15rpx;
  border-radius: 8rpx;
  position: relative;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
  font-size: 24rpx;
}

.reply-user {
  font-weight: bold;
  color: #333;
  margin-right: 10rpx;
}

.reply-time {
  color: #999;
  margin-right: 10rpx;
}

.reply-to {
  color: #007aff;
}

.reply-actions {
  margin-top: 10rpx;
}

.reply-content {
  color: #666;
  line-height: 1.4;
  font-size: 26rpx;
}

/* 嵌套回复样式 */
.nested-replies {
  margin-top: 15rpx;
  padding-left: 30rpx;
  border-left: 2rpx solid #ddd;
}

.nested-reply-item {
  background-color: #f0f0f0;
  padding: 12rpx;
  margin-bottom: 12rpx;
  border-radius: 6rpx;
}

.nested-reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 6rpx;
  font-size: 22rpx;
}

.nested-reply-user {
  font-weight: bold;
  color: #333;
  margin-right: 8rpx;
}

.nested-reply-time {
  color: #999;
  margin-right: 8rpx;
}

.nested-reply-to {
  color: #007aff;
}

.nested-reply-content {
  color: #666;
  line-height: 1.3;
  font-size: 24rpx;
}

.expand-btn,
.expand-nested-btn {
  color: #007aff;
  font-size: 24rpx;
  text-align: center;
  padding: 8rpx 0;
  margin-top: 10rpx;
}

/* 回复输入框样式 */
.comment-input {
  display: flex;
  align-items: center;
  background-color: #fff;
  padding: 20rpx;
  border-radius: 10rpx;
  position: sticky;
  bottom: 0;
}

.comment-input .input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  background-color: #f5f5f5;
  border-radius: 40rpx;
  margin-right: 20rpx;
}

.comment-input .submit-btn {
  width: 120rpx;
  height: 80rpx;
  line-height: 80rpx;
  background-color: #007aff;
  color: #fff;
  border-radius: 40rpx;
  font-size: 28rpx;
}
</style>